package msg

import (
  "fmt"
  . "gitee.com/yizhisamoye/GoWeChat/entity/common"
  "reflect"
)

type WxRespMsg struct {
  ToUserName string `xml:"ToUserName"`
  FromUserName string
  CreateTime int
  MsgType string
  Content      string
  Image        MediaEntity
  Voice        MediaEntity
  Video        MediaEntity
  Music        MediaEntity
  ArticleCount int
  Articles     []MediaEntity
}

func(respMsg WxRespMsg)ConvertToWxXml()string{
  typ:=reflect.TypeOf(respMsg)
  val:=reflect.ValueOf(respMsg)
  resultXml:=""
  num:=val.NumField()
  for i:=0;i<num;i++{
    fieldName:=typ.Field(i).Name
    fieldType:=typ.Field(i).Type
    if fieldType.Kind()==reflect.String{
      fieldVal:=val.Field(i).String()
      resultXml+=fmt.Sprintf(`<%s>%s</%s>`,fieldName,fieldVal,fieldName)
    }else if fieldType.Kind()==reflect.Int||fieldType.Kind()==reflect.Int64{
      fieldVal:=val.Field(i).Int()
      resultXml+=fmt.Sprintf(`<%s>%d</%s>`,fieldName,fieldVal,fieldName)
    }else if fieldType.Name()=="MediaEntity"{
      fieldVal:=val.Field(i).Interface().(MediaEntity)
      resultXml+=fmt.Sprintf(`<%s>%s</%s>`,fieldName,fieldVal.ToXml(true),fieldName)
    }else if fieldType.Kind()==reflect.Slice&&fieldType.Elem().Name()=="MediaEntity"{
      resultXml+="<Articles>"
      fieldVal:=val.Field(i).Interface().([]MediaEntity)
      for _,v:=range fieldVal{
        resultXml+=fmt.Sprintf(`<item>%s</item>`,v.ToXml(true))
      }
      resultXml+="</Articles>"
    }
  }
  resultXml="<xml>"+resultXml+"</xml>"
  return resultXml
}
